package com.chinaums.xm.wechat.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.chinaums.xm.wechat.WeixinConstant;
import com.chinaums.xm.wechat.commons.CheckUtil;
import com.chinaums.xm.wechat.commons.MessageUtil;
import com.chinaums.xm.wechat.domain.juhe.CertInfo;
import com.chinaums.xm.wechat.domain.juhe.PhoneInfo;
import com.chinaums.xm.wechat.domain.wechat.AuthorizationAccessToken;
import com.chinaums.xm.wechat.service.AggregationService;
import com.chinaums.xm.wechat.service.wechat.CommonService;
import com.chinaums.xm.wechat.service.wechat.MassService;
import com.chinaums.xm.wechat.service.wechat.MaterialService;
import com.chinaums.xm.wechat.service.wechat.MenuService;
import com.chinaums.xm.wechat.service.wechat.MessageService;
import com.chinaums.xm.wechat.service.wechat.UserService;
import com.chinaums.xm.wechat.service.wechat.WebPageService;
import com.chinaums.xm.wechat.util.IdCardValidator;
import com.chinaums.xm.wechat.util.PhoneValidator;

import io.swagger.annotations.ApiOperation;

@RequestMapping("/wechat")
@RestController
public class WeixinController {

	private static final Logger logger = LoggerFactory.getLogger(WeixinController.class);

	@Resource
	private CommonService weixinService;
	
	@Resource
	private MenuService menuService;
	
	@Resource
	private MessageService MessageService;
	
	@Resource
	private WebPageService webPageService;
	
	@Resource
	private MassService massService;
	
	@Resource
	private MaterialService materialService;
	
	@Resource
	private AggregationService aggregationService;
	
	@Resource
	private UserService userService;
	
	
	/**
	 * 后台服务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "消息服务", notes = "消息服务")
	@RequestMapping(method = RequestMethod.POST)
	public String sendMsg(final HttpServletRequest request, final HttpServletResponse response) {
		try {
			final Map<String, String> requestMap = MessageUtil.xmlToMap(request);
			logger.info("接收微信请求报文:{}", requestMap);
			final String fromUserName = requestMap.get("FromUserName");
			final String toUserName = requestMap.get("ToUserName");
			final String msgType = requestMap.get("MsgType");
			logger.info("消息类型:{}", msgType);
			String message = "";
			if (WeixinConstant.MESSAGE_TEXT.equals(msgType)) {
				final String content = requestMap.get("Content");// 微信用户主动发送的消息内容
				if ("?".equals(content) || "？".equals(content)) {
					message = MessageService.genText(toUserName, fromUserName, MessageUtil.menuList());
				} else {
					if(content.length() == 11){
						if(PhoneValidator.validate(content)){
							final Optional<PhoneInfo> phoneInfo = aggregationService.getMoboleInfo(content);
							if(phoneInfo.isPresent()){
								final String province = phoneInfo.get().getProvince(); // 所属省份
								final String city = phoneInfo.get().getCity(); // 所属城市
								final String company = phoneInfo.get().getCompany(); // 所属运营商
								final String areacode = phoneInfo.get().getAreacode(); // 区域编码
								final String zip = phoneInfo.get().getZip(); // 邮政编码
								final StringBuffer sb = new StringBuffer();
								sb.append("手机号："+content+"\n");
								sb.append("所属省份："+province+"\n");
								sb.append("所属城市："+city+"\n");
								sb.append("所属运营商："+company+"\n");
								sb.append("地区编码："+areacode+"\n");
								sb.append("邮政编码："+zip);
								message = MessageService.genText(toUserName, fromUserName, sb.toString());
							}
						} else {
							message = MessageService.genText(toUserName, fromUserName, "请输入正确的手机号!");
						}
					} else if(Arrays.asList(15,18).contains(content.length())){
						if(IdCardValidator.validate(content).isSuccess()){
							final Optional<CertInfo> moboleInfo = aggregationService.getCertInfo(content);
							if(moboleInfo.isPresent()){
								final String area = moboleInfo.get().getArea();// 地区
								final String sex = moboleInfo.get().getSex(); // 性别
								final String birthday = moboleInfo.get().getBirthday(); // 出生日期
								final StringBuffer sb = new StringBuffer();
								sb.append("身份证号："+content+"\n");
								sb.append("所属区域："+area+"\n");
								sb.append("出生日期："+birthday+"\n");
								sb.append("性        别："+sex);
								message = MessageService.genText(toUserName, fromUserName, sb.toString());
							}
						} else {
							message = MessageService.genText(toUserName, fromUserName, "请输入正确的证件号!");
						}
					} else {
						message = MessageService.genText(toUserName, fromUserName, "请输入正确的证件号或者手机号!");
					}
				}
				/*if ("1".equals(content)) {
					message = MessageService.genText(toUserName, fromUserName, MessageUtil.first()); // 回复图文消息
				} else if ("2".equals(content)) {
					message = MessageService.genNews(toUserName, fromUserName); // 回复图文消息
				} else if ("3".equals(content)) {
					message = MessageService.genImage(toUserName, fromUserName);
				} else if ("?".equals(content) || "？".equals(content)) {
					message = MessageService.genText(toUserName, fromUserName, MessageUtil.menuList());
				} else {
					final Optional<String> moboleInfo = aggregationService.getMoboleInfo(content);
					if(moboleInfo.isPresent()){
						final String info = moboleInfo.get();
						message = MessageService.genText(toUserName, fromUserName, info);
					}
				}*/
			} else if (WeixinConstant.MESSAGE_EVENT.equals(msgType)) {
				final String eventType = requestMap.get("Event");
				if(WeixinConstant.MESSAGE_SUBSCRIBE.equals(eventType)){
					message = MessageService.genText(toUserName, fromUserName, MessageUtil.menuList());
				} else if(WeixinConstant.MESSAGE_UNSUBSCRIBE.equals(eventType)){
					message = MessageService.genText(toUserName, fromUserName, MessageUtil.unsubscribe());
				} else if(WeixinConstant.MESSAGE_CLICK.equals(eventType)){
					final String eventKey = requestMap.get("EventKey");
					if(eventKey.equals("button1")){
						message = MessageService.genText(toUserName, fromUserName, "您点击了菜单1");
					} else if(eventKey.equals("button3")) {
						message = MessageService.genText(toUserName, fromUserName, "您点击了子菜单1");
					}
				} else if(WeixinConstant.MESSAGE_VIEW.equals(eventType)){
					final String eventKey = requestMap.get("EventKey");
					message = MessageService.genText(toUserName, fromUserName, "你跳转的URL为:" + eventKey);
				}
			}
			logger.info("响应报文:{}", message);
			return message;
		} catch (IOException e) {
			logger.error(e.getLocalizedMessage(), e);
			return "";
		} catch (DocumentException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 后台服务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value = "消息服务", notes = "消息服务")
	@RequestMapping(value = { "/sendMsg" }, method = RequestMethod.GET)
	public String sendAllMessage(final HttpServletRequest request, final HttpServletResponse response) {
		final boolean result = massService.sendNewsMsgAll();
		if(result){
			return "success";
		}
		return "error";
	}
	
	/**
	 * 微信验证签名
	 * 
	 * @param request
	 * @param response
	 * @param reqIds
	 * @return
	 */
	@ApiOperation(value = "验证签名", notes = "验证签名")
	@RequestMapping(method = RequestMethod.GET)
	public String checkSignature(final HttpServletRequest request, final HttpServletResponse response) {
		final String signature = request.getParameter("signature");
		logger.info("签名信息:{}", signature);
		final String timestamp = request.getParameter("timestamp");
		final String nonce = request.getParameter("nonce");
		final String echostr = request.getParameter("echostr");
		logger.info("接受微信随机字符串:{}", echostr);
		final boolean result = CheckUtil.checkSignature(signature, timestamp, nonce);
		logger.info("签名结果:{}", result);
		if (result) {
			return echostr;
		} else {
			return "";
		}
	}
	
	@ApiOperation(value = "菜单创建", notes = "菜单创建")
	@RequestMapping(value = { "/createMenu" }, method = RequestMethod.GET)
	public void testCreateMenu() throws UnsupportedEncodingException{
		final boolean result = menuService.createMenu();
		if(result){
			logger.info("菜单创建成功");
		} else {
			logger.debug("菜单创建失败");
		}
	}
	
	@ApiOperation(value = "菜单创建", notes = "菜单创建")
	@RequestMapping(value = { "/createIndividuationMenu" }, method = RequestMethod.GET)
	public void testCreateIndividuationMenu() throws UnsupportedEncodingException{
		final boolean result = menuService.createIndividuationMenu();
		if(result){
			logger.info("菜单创建成功");
		} else {
			logger.debug("菜单创建失败");
		}
	}
	
	
	@ApiOperation(value = "菜单查询", notes = "菜单查询")
	@RequestMapping(value = { "/queryIndividuationMenu" }, method = RequestMethod.GET)
	public void testQueryIndividuationMenu(){
		menuService.queryIndividuationMenu();
	}
	
	@ApiOperation(value = "菜单查询", notes = "菜单查询")
	@RequestMapping(value = { "/queryMenu" }, method = RequestMethod.GET)
	public void testQueryMenu(){
		menuService.queryMenu();
	}
	
	@ApiOperation(value = "菜单删除", notes = "菜单删除")
	@RequestMapping(value = { "/deleteMenu" }, method = RequestMethod.GET)
	public void testDeleteMenu(){
		final boolean result = menuService.deleteMenu();
		if(result){
			logger.info("菜单删除成功");
		} else {
			logger.debug("菜单删除失败");
		}
	}
	
	@ApiOperation(value = "菜单配置查询", notes = "菜单配置查询")
	@RequestMapping(value = { "/queryMenuSetting" }, method = RequestMethod.GET)
	public void testQueryMenuSetting(){
		menuService.queryMenuSetting();
	}
	
	@ApiOperation(value = "上传临时素材", notes = "上传临时素材")
	@RequestMapping(value = { "/uploadTempMaterial" }, method = RequestMethod.GET)
	public void uploadTempMaterial(){
		final Optional<String> response = materialService.mediaUpLoad("image", "D:\\1.jpg", "", new HashMap<>());
		if(response.isPresent()){
			final String mediaId = response.get();
			logger.info("mediaId is:{}",mediaId);
		}
	}
	
	@ApiOperation(value = "获取网页授权信息", notes = "获取网页授权信息")
	@RequestMapping(value = { "/getUserInfo" }, method = RequestMethod.GET)
	public void getUserInfo(final HttpServletRequest request,final HttpServletResponse response,
			final String code,final String state) throws IOException{
		logger.info("code is:{} and state is:{}",code,state);
		final Optional<AuthorizationAccessToken> accessToken = webPageService.getAccessTokenByCode(code);
		if(accessToken.isPresent()){
			final String openid = accessToken.get().getOpenid();
			final String token = accessToken.get().getAccess_token();
			webPageService.getUserInfo(token, openid);
		}
		response.sendRedirect("http://www.xmylsw.com");
	}
	
}
